package org.rain.core.rbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.rain.common.anno.AutoLog;
import org.rain.common.exception.BaseException;
import org.rain.common.model.R;
import org.rain.common.util.bean.Beans;
import org.rain.common.util.Strs;
import org.rain.core.BaseController;
import org.rain.core.querygen.QueryWrapperGenerate;
import org.rain.core.rbac.model.entity.SysUser;
import org.rain.core.rbac.model.req.UserReq;
import org.rain.core.rbac.model.resp.UserResp;
import org.rain.core.rbac.service.ISysUserService;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * created by   on 2025年4月9日 23:03:21
 * <br/>
 * User表控制器
 * <br/>
 */
@RestController
@RequestMapping("/sys/user")
@Tag(name = "用户表")
public class SysUserController extends BaseController<SysUser, ISysUserService> {

    /**
     * 分页查询
     */
    @AutoLog
    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "根据id查询对应的实体数据数据")
    //@Cacheable(value = "user", key = "1234")
    public R<IPage<SysUser>> page(@ParameterObject UserReq userdata,
                                  @RequestParam(defaultValue = "1") Long pageNo,
                                  @RequestParam(defaultValue = "10") Long pageSize) {
        QueryWrapper<SysUser> queryWrapper = QueryWrapperGenerate.init(userdata);
        IPage<SysUser> page = new Page<>(pageNo, pageSize);
        return R.success(baseService.page(page, queryWrapper));
    }

    /**
     * 根据id查询数据
     */
    @GetMapping("/queryById")
    @Operation(summary = "根据id查询", description = "根据id查询数据")
    protected R<UserResp> queryById(String id) {
        SysUser sysUser = baseService.getById(id);
        return R.success(sysUser.toResp());
    }

    /**
     * 新增或编辑数据
     */
    @PostMapping("/addOrUpdate")
    @Operation(summary = "新增或编辑", description = "根据有无主键id,新增或编辑数据")
    protected R<String> addOrUpdate(@RequestBody UserReq userdata) {
        SysUser sysUser = Beans.copyProperties(userdata, SysUser.class);
        baseService.saveOrUpdate(sysUser);
        return R.success(sysUser.getId() == null ? "新增成功" : "编辑成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除", description = "根据id删除数据")
    protected R<String> delete(@Parameter(description = "主键id") String ids) {
        if (Strs.isEmpty(ids)) {
            throw new BaseException("删除接口的ids不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        baseService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

}